package com.cloud.knowledge.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloud.knowledge.model.Knowledge;
import com.cloud.platform.IDao;
import com.cloud.platform.json.JSONArray;
import com.cloud.platform.json.JSONObject;
import com.cloud.platform.util.Constants;
import com.cloud.platform.util.StringUtil;
import com.cloud.platform.util.TreeUtil;

@Component("knowledgeService")
public class KnowledgeService {

	@Autowired
	private IDao dao;
	
	/**
	 * save knowledge info for knowledges manage
	 * 
	 * @param userId
	 * @param knowledgeInfo
	 * @throws Exception
	 */
	public void saveKnowledgeInfo(String userId, String knowledgeInfo) throws Exception {
		if(StringUtil.isNullOrEmpty(knowledgeInfo)) {
			return;
		}
		
		JSONArray info = new JSONArray(knowledgeInfo);
		
		// iterate every knowledge info
		for(int i = 0; i < info.length(); i++) {
			JSONObject knowledge = info.getJSONObject(i);
			Knowledge k = null;
			
			// add knowledge
			if(StringUtil.isNullOrEmpty(knowledge.getString("i"))) {
				k = new Knowledge();
				k.setId(Constants.getID());
				k.setUid(userId);
				k.setIsNode(knowledge.getString("nd"));
				k.setCreateTime(new Date());
			}
			// modify knowledge or delete knowledge
			else {
				k = (Knowledge) dao.getObject(Knowledge.class, knowledge.getString("i"));
				
				if(knowledge.length() == 1) {  // if info only has id, is delete
					dao.removeObject(k);
					continue;
				}
			}
			
			// knowledge name
			if(knowledge.has("n")) {
				k.setName(knowledge.getString("n"));
			}
			
			// knowledge parent node id
			if(knowledge.has("pi")) {
				k.setParentId(knowledge.getString("pi"));
			}
			
			// knowledge color
			if(knowledge.has("c")) {
				k.setColor(knowledge.getString("c"));
			}
			
			dao.saveObject(k);
		}
	}
	
	/**
	 * search user knowledges
	 * 
	 * @param userId
	 * @return
	 */
	public List<Knowledge> searchKnowledges(String userId) {
		if(StringUtil.isNullOrEmpty(userId)) {
			return new ArrayList();
		}
		
		String hql = "from Knowledge where uid = ?";
		List knowledges = dao.getAllByHql(hql, userId);
		
		return TreeUtil.sortTree(knowledges);
	}
}
